const { getCaseKnex } = require('../database/knex');

/**
 * FastPassPlugin
 * 快进快出分析后端插件
 */
const FastPassPlugin = {
    id: 'fast_pass',
    name: '快进快出',
    version: '1.0.0',
    description: '检测资金短时间内流入后迅速流出的异常模式',
    type: 'analysis',
    params: [
        { key: 'timeWindowHours', label: '时间窗口(小时)', type: 'number', default: 2, min: 1, max: 48 },
        { key: 'minAmount', label: '最小金额', type: 'number', default: 50000, min: 0 }
    ],

    run: async (context, params = {}) => {
        const { caseId, dbPath } = context;
        // params might come from the UI config panel
        const timeWindowHours = Number(params.timeWindowHours) || 2;
        const minAmount = Number(params.minAmount) || 50000;
        const ratio = 0.8; // Hardcoded or param

        if (!caseId || !dbPath) {
            throw new Error('Context missing caseId or dbPath');
        }

        const knex = getCaseKnex(caseId, dbPath);

        // Use raw SQL for complex join
        // Note: Backend doesn't have "currentSubject" if we run globally.
        // If we run for specific subject, we need to filter by subject's accounts.
        // But passing "subject" object to backend is complex. 
        // We usually just pass "card_number" list OR "subjectId" and let backend lookup accounts.

        // For simplicity now, let's assume GLOBAL analysis if no accounts provided?
        // Or if params has 'accounts'.
        // The original FastPassAnalyzer logic: if targetSubject, filter accounts.

        // Let's modify run to accept 'subjectId' in context? 
        // Or UI passes 'accounts' in params?
        // UI `Analysis.vue` passes params. It can pass `accounts`.

        let accountFilter = '';
        if (params.accounts && Array.isArray(params.accounts) && params.accounts.length > 0) {
            const accList = params.accounts.map(a => `'${a}'`).join(',');
            accountFilter = `AND card_number IN (${accList})`;
        } else if (params.subjectId) {
            // If subjectId provided but no accounts, backend might need to lookup.
            // But let's assume UI resolves accounts for now to keep Plugin simple.
        }

        const sql = `
            WITH InTransactions AS (
                SELECT 
                    card_number,
                    customer_name,
                    transaction_time,
                    transaction_amount as in_amount,
                    counterparty_name as in_from
                FROM bank_transactions
                WHERE case_id = ?
                    AND debit_credit_flag = '借'
                    AND transaction_amount >= ?
                    ${accountFilter}
            ),
            OutTransactions AS (
                SELECT 
                    card_number,
                    transaction_time,
                    transaction_amount as out_amount,
                    counterparty_name as out_to
                FROM bank_transactions
                WHERE case_id = ?
                    AND debit_credit_flag = '贷'
                    ${accountFilter}
            )
            SELECT 
                i.card_number,
                i.customer_name,
                i.transaction_time as in_time,
                i.in_amount,
                i.in_from,
                o.transaction_time as out_time,
                o.out_amount,
                o.out_to,
                CAST((julianday(o.transaction_time) - julianday(i.transaction_time)) * 24 AS REAL) as hours_diff
            FROM InTransactions i
            JOIN OutTransactions o ON i.card_number = o.card_number
            WHERE o.transaction_time > i.transaction_time
                AND (julianday(o.transaction_time) - julianday(i.transaction_time)) * 24 <= ?
                AND ABS(o.out_amount) >= i.in_amount * ?
            ORDER BY hours_diff ASC, i.in_amount DESC
            LIMIT 100
        `;

        const result = await knex.raw(sql, [
            caseId, minAmount,
            caseId,
            timeWindowHours,
            ratio
        ]);

        return result;
    }
};

module.exports = FastPassPlugin;
